<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/8/3
 * Time: 9:48
 */

namespace app\admin\model;


use app\api\model\user\Users;
use app\common\lib\rongcloud\RongCloud;
use app\common\model\ApiResponse;
use app\common\model\Chat;
use app\common\model\teacher\TeacherDegree;
use app\common\model\teacher\TeacherEssay;
use Exception;
use think\Cache;
use think\Db;
use think\Log;
use think\Model;

/**
 * @deprecated
 *
 * Class Teacher
 * @package app\admin\model
 *
 * @property mixed id
 * @property mixed username
 * @property mixed password
 * @property mixed realname
 * @property mixed avatar
 * @property mixed gender
 * @property mixed intro
 * @property mixed success_rate
 * @property mixed num_followed
 * @property mixed chat_token
 * @property mixed degree_id
 * @property mixed rank
 * @property mixed hide
 * @property mixed recommend
 * @property mixed num_essay
 * @property mixed num_speaking
 * @property mixed num_curriculum_video
 * @property mixed qualification_certificate
 *
 * 扩展属性
 * @property string token
 */
class Teacher extends Model
{
    protected $table = 'teacher';
    protected $pk = 'id';
    protected $field = [
        'id',
        'username',
        'password',
        'realname',
        'avatar',
        'gender',
        'intro',
        'success_rate',
        'chat_token',
        'degree_id',
        'rank',
        'hide',
        'recommend',
        'qualification_certificate',
    ];

    public static function passwordEncrypt($passwordText) {
        return password_hash($passwordText, PASSWORD_DEFAULT);
    }
    public static function passwordVerify($passwordText, $passwordHash) {
        return password_verify($passwordText, $passwordHash);
    }

    const DEFAULT_AVATAR = '/static/img/default_avatar.png';

    /**
     * 获取聊天服务器的id和token
     *
     * @param $data
     * @return array|mixed
     */
    public static function chatToken($data) {

        if ($data instanceof Model) $data = $data->toArray();
        elseif ($data instanceof \stdClass) $data = (array)$data;

        $chatId = Chat::getChatId('t'.$data['id']);
        $chat = Chat::cache($chatId);
        if ($chat) {
            return $chat;
        }

        $rong = RongCloud::getInstance();
        $name = !empty($data['realname']) ? $data['realname'] : $data['username'];
        $avatar = !empty($data['avatar']) ? $data['avatar'] : Users::defaultAvatar();
        $re = $rong->User()->getToken($chatId, $name, $avatar);
        $chat_token = $re['token'];

        $chat = ['id' => $chatId, 'token' => $chat_token, 'avatar'=>$avatar, 'name' => $name,];
        Chat::cache($chatId, $chat);

        return $chat;
    }

    public static function manageList(int $limit, int $offset, $keywords = null) {

        $filter = $keywords ? " AND realname like :kw " : null;
        $params = ['limit' => $limit, 'offset' => $offset];

        if ($keywords) $params['kw'] = "%$keywords%";

        $sql = <<<SQL
SELECT * FROM teacher
WHERE TRUE {$filter}
ORDER BY id DESC 
LIMIT :limit OFFSET :offset
SQL;
        $list = Db::query($sql, $params);

        $sql = <<<SQL
SELECT count(id) as num FROM teacher
WHERE TRUE {$filter}
SQL;
        unset($params['limit'], $params['offset']);
        $re = Db::query($sql, $params);
        $total = $re[0]['num'] ?? 0;

        foreach ($list as & $item) {
            unset($item['password']);
        }

        return PageResponse::success($list, $total);
    }
    
    public static function listNames() {
        $sql = <<<SQL
SELECT id,username AS name,realname,avatar FROM teacher
SQL;
        $list = Db::query($sql);
        return $list;
    }

    public static function checkUsername($username) {
        $sql = <<<SQL
SELECT exists( SELECT id FROM teacher WHERE username=:username LIMIT 1 ) e
SQL;
        $re = Db::query($sql, ['username' => $username]);
        return $re[0]['e'] ?? false;
    }

    /**
     *
     * @param $id
     * @param $hide
     */
    public static function setHide($id, $hide) {
        $sql = <<<SQL
UPDATE teacher SET hide = :hide WHERE id = :id
SQL;
        Db::query($sql, ['id' => $id, 'hide' => $hide]);
    }

    /**
     * 统计发表图文数
     *
     * @param $id
     */
    public static function countNumEssay($id) {
        $sql = <<<SQL
UPDATE teacher SET num_essay = (
SELECT count(*) FROM teacher_essay e WHERE e.teacher_id=teacher.id AND e.hide=FALSE 
) WHERE id=:id
SQL;
        Db::execute($sql, ['id' => $id,]);
    }

    /**
     * 统计发表语音数
     *
     * @param $id
     */
    public static function countNumSpeaking($id) {
        $sql = <<<SQL
UPDATE teacher SET num_speaking = (
SELECT count(*) FROM teacher_speaking e WHERE e.teacher_id=teacher.id
) WHERE id=:id
SQL;
        Db::execute($sql, ['id' => $id]);
    }

    /**
     * 统计视频数
     *
     * @param $id
     */
    public static function countNumVideo($id) {
        $sql = <<<SQL
UPDATE teacher SET num_curriculum_video = (
SELECT count(*) FROM curriculum_video e WHERE e.video_teacher=teacher.id AND e.hide=FALSE 
) WHERE id=:id
SQL;
        Db::execute($sql, ['id' => $id]);
    }

    /**
     * @param $username
     * @return null|static
     */
    public static function getByUserName($username) {
        return self::get(['username' => $username]);
    }

    /**
     * @return array
     */
    public function info() {
        return [
            'id' => $this->id,
            'username' => $this->username,
            'realname' => $this->realname,
            'avatar' => $this->avatar ? $this->avatar : self::DEFAULT_AVATAR,
            'gender' => $this->gender,
            'degree' => $this->getDegreeName(),
            'success_rate' => $this->success_rate,
            'intro' => $this->intro,
            'num_followed' => $this->num_followed,
            'num_essay' => $this->num_essay,
            'num_speaking' => $this->num_speaking,
            'num_curriculum_video' => $this->num_curriculum_video,
            'role' => 'admin',
            'roles' => ['admin'],
        ];
    }

    public function getDegreeName() {
        $sql = 'select name from teacher_degree where id=:id';
        $re = Db::query($sql, ['id' => $this->degree_id]);
        return $re[0]['name'] ?? '';
    }

}